package com.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(CorsFilter.class);

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        HttpServletRequest reqs = (HttpServletRequest) req;

//        System.out.println("****************************" + reqs.getRequestURI());
        
        if ("/".equals(reqs.getRequestURI())) {
            res.getWriter().print("OK");
            return;
        }

        response.setHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true"); //若要返回cookie、携带seesion等信息则将此项设置true
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS, POST, GET, DELETE"); //允许跨域的请求方式
        response.setHeader("Access-Control-Max-Age", "3600"); //预检请求的间隔时间
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, mode, token, authorization, User-Token, Language"); //允许跨域请求携带的请求头
        response.setHeader("Cache-Control", "no-store"); // 发现可高速缓存的 SSL
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setHeader("strict-transport-security","max-age=16070400; includeSubDomains"); //简称为HSTS。它允许一个HTTPS网站，要求浏览器总是通过HTTPS来访问它
        response.setHeader("Content-Security-Policy","default-src 'self'"); //这个响应头主要是用来定义页面可以加载哪些资源，减少XSS的发生
        response.setHeader("X-Content-Type-Options","nosniff"); //互联网上的资源有各种类型，通常浏览器会根据响应头的Content-Type字段来分辨它们的类型。通过这个响应头可以禁用浏览器的类型猜测行为
        response.setHeader("X-XSS-Protection","1; mode=block"); //1; mode=block：启用XSS保护，并在检查到XSS攻击时，停止渲染页面
        response.setHeader("X-Frame-Options","SAMEORIGIN"); //SAMEORIGIN：不允许被本域以外的页面嵌入；

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

